package com.network;

import java.io.DataInputStream;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServer extends Thread{
    private Socket socket;
    TcpServer(Socket serverSocket){
        this.socket = serverSocket;
    }

    @Override
    public void run() {
        System.out.println(socket.getRemoteSocketAddress() + "已上线");
        ConnectionsControler.addList(socket);
        try{
            DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
            while(true){
                try{
                    String msg = dataInputStream.readUTF();
                    System.out.println(msg);
                    ConnectionsControler.tranMsgList(msg, socket);
                }catch (Exception e){
                    System.out.println(ConnectionsControler.removeList(socket));
                    System.out.println(socket.getRemoteSocketAddress() + "已下线");
                    try{
                        socket.close();
                    }
                    catch (Exception te){
                        System.out.println(te.getMessage());

                    }
                    break;
                }
            }
        }catch (Exception e){
            throw new IllegalArgumentException();
        }
    }
}
